package com.we.risk.phoneRecord.stage2.dimuser;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Deprecated
public class TableUserAddress {
    public static final String KFKTABLE = "fdm.hhl01_user_address_1029";
    public static final String QUERYSQL =
            "select uid, updated_at,"
                    + " province, city, county"
                    + " from "
                    + KFKTABLE
                    + " where deleted_at is null "
                    + "and updated_at is not null "
                    + "and province is not null "
                    + "and city is not null "
                    + "and county is not null";

    public long uid;
    public String province;
    public String city;
    public String county;
    public int updated_at;

    public TableUserAddress() {}

    public TableUserAddress(long uid, String province, String city, String county, int updated_at) {
        this.uid = uid;
        this.province = province;
        this.city = city;
        this.county = county;
        this.updated_at = updated_at;
    }

    public static Logger LOG = LoggerFactory.getLogger(TableUserAddress.class);

    public static TableUserAddress init(long uid) {
        return new TableUserAddress(uid, "", "", "", -1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserAddress.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserAddress>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserAddress.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserAddress>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserAddress> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TableUserAddress-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserAddress>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserAddress> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserAddress>, String>() {
                                    ValueState<TableUserAddress> tableUserAddressVSatate;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tableUserAddressVSatate =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableUserAddress>(
                                                                        "TableUserAddressVSatate",
                                                                        TableUserAddress.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserAddress> value,
                                            Collector<String> out)
                                            throws Exception {
                                        try {
                                            long uid = value.f1.getUid();
                                            int updated_at = value.f1.getUpdated_at();
                                            String province = value.f1.getProvince();
                                            String city = value.f1.getCity();
                                            String county = value.f1.getCounty();

                                            TableUserAddress tmpState =
                                                    tableUserAddressVSatate.value();
                                            TableUserAddress curSTate =
                                                    tmpState == null
                                                            ? TableUserAddress.init(uid)
                                                            : tmpState;

                                            if (updated_at > curSTate.getUpdated_at()) {
                                                if (!province.equals(curSTate.province)
                                                        || !city.equals(curSTate.getCity())
                                                        || !county.equals(curSTate.getCounty())) {
                                                    JSONObject json = new JSONObject();
                                                    json.put("uid", uid);
                                                    json.put("ad_prov", province);
                                                    json.put("ad_city", city);
                                                    json.put("ad_county", county);

                                                    out.collect(json.toString());

                                                    curSTate.updated_at = updated_at;
                                                    curSTate.province = province;
                                                    curSTate.city = city;
                                                    curSTate.county = county;
                                                    tableUserAddressVSatate.update(curSTate);
                                                }
                                            }
                                        } catch (Exception e) {
                                            LOG.error(
                                                    "TableUserAddress flatMap Exception: "
                                                            + e.toString());
                                            LOG.error(
                                                    "TableUserAddress flatMap Exception input: "
                                                            + value);
                                            e.printStackTrace();
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getUpdated_at() {
        return updated_at;
    }

    public String getProvince() {
        return province;
    }

    public String getCity() {
        return city;
    }

    public String getCounty() {
        return county;
    }
}
